const mongoose = require('mongoose')

mongoose.connect('mongodb://localhost/playground')
    .then(() => console.log('数据库连接成功'))
    .catch(err => console.log(err, '数据库连接失败'))

const postSchema = new mongoose.Schema({
    title: {
        type: String,
        required: [true, '请传入文章标题'],
        minlength: [2, '文章长度不能小于2'],
        maxlength: [5, '文章长度不能大于5'],
        trim: true
    },
    age: {
        type: Number,
        min: [18, '年龄不能小于18岁'],
        max: [100, '年龄不能大于100岁']
    },
    publishDate: {
        type: Date,
        default: Date.now
    },
    category: {
        type: String,
        enum: {
            values: ['html', 'css', 'javascript', 'node.js'],
            message: '分类名称要在一定的范围内才可以'
        },
    },
    author: {
        type: String,
        validate: {
            validator: v => {
                // 返回布尔值
                // true 验证成功
                // false 验证失败
                // v 是要验证的值
                return v && v.length > 4
            },
            // 自定义错误信息
            message: '传入的值不符合验证规则'
        }
    }
})

const Post = mongoose.model('Post', postSchema)

Post.create({ title: 'edee', age: 36, category: 'java', author: 'bd' })
    .then(result => console.log(result))
    .catch(error => {
        const err = error.errors;
        for (var attr in err) {
            console.log(err[attr]['message']);

        }
    })